#include "nn.h"
#include "pair.h"
#include "pubsub.h"
#include "pipeline.h"
#include "tcp.h"

#include <time.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>

#include "pipeline.h"
 
#define NODE0 "node0"
#define NODE1 "node1"
#define DATE "DATE"
#define DATE1 "123"
#define DATE2 "456"
#define DATE3 "7890"
#define SOCKET_ADDR "ipc:///tmp/pipeline.ipc"
 
char *date(void)
{
        time_t raw = time(&raw);
        struct tm *info = localtime(&raw);
        char *text = asctime(info);
 
        text[strlen(text) - 1] = '\0';
 
        return text;
}
 
int node0(const char *url)
{
        int sock = nn_socket(AF_SP, NN_PUSH);
        int bytes;
 
        assert(sock >= 0);
        assert(nn_bind(sock, url) >= 0);
        
        bytes = nn_send(sock, DATE, sizeof(DATE)+1, 0);
        printf("NODE0: PUSH DATE %s\n", DATE);
        sleep(1);

        bytes = nn_send(sock, DATE1, sizeof(DATE1)+1, 0);
        printf("NODE0: PUSH DATE %s\n", DATE1);
        sleep(1);

        bytes = nn_send(sock, DATE2, sizeof(DATE2)+1, 0);
        printf("NODE0: PUSH DATE %s\n", DATE2);
        sleep(1);

        bytes = nn_send(sock, DATE3, sizeof(DATE3)+1, 0);
        printf("NODE0: PUSH DATE %s\n", DATE3);
        sleep(1);
 
        return nn_shutdown (sock, 0);
}
 
int node1(const char *url)
{
        char *buf = NULL;
        int bytes = -1;
        int sock = nn_socket(AF_SP, NN_PULL);
 
        assert(sock >= 0);
        assert(nn_connect(sock, url) >= 0);
 
        /* Receive */
        while (1)
        {
                bytes = nn_recv (sock, &buf, NN_MSG, 0);
                if (bytes > 0) {
                        printf("NODE1: PULL DATE %s\n", buf);
                        nn_freemsg(buf);
                }
                
        }
 
        return nn_shutdown (sock, 0);
}
 
int main (int argc, char **argv)
{
        if (argc == 2 && strncmp(NODE0, argv[1], strlen(NODE0)) == 0) {
                return node0(SOCKET_ADDR);
        } else if (argc == 2 && strncmp(NODE1, argv[1], strlen(NODE1)) == 0) {
                return node1(SOCKET_ADDR);
        } else {
                fprintf (stderr, "Usage: reqrep %s|%s <ARG> ...\n", NODE0, NODE1);
                return 1;
        }
}